<?php
class Relations_model extends Model {

	function Relations_model() {
		parent::Model();
	}
	
	/**
	 * Returns the next version number of the databse
	 */
	private function get_next_db_version() {
		$this->db->query('UPDATE cr_config SET value = LAST_INSERT_ID(value+1) WHERE name = \'db_version\'');
		$query = $this->db->query('SELECT LAST_INSERT_ID() last_id');
		$array = $query->result_array();
		return $array[0]['last_id'];
	}
	
	function get_relations($branch, $oneway = true) {
		if (is_numeric($branch)) {
			if ($oneway)
				$nbch = 'bch1';
			else
				$nbch = 'bch2';
			$sql = 'SELECT *, cr_branches.name as \'bchname\', cr_packages.name as \'pkgname\', ' .
					'concat(cr_packages.name, \' - \', cr_branches.name) as \'uf_bch2\' ' .
					'FROM cr_bch_relations ' .
					'JOIN cr_branches ON bch2 = branch_id ' .
					'JOIN cr_packages ON package = pkg_id ' .
					'WHERE '.$nbch.' = '.$branch;
			$query = $this->db->query($sql);
			return $query->result_array();
		}
		return null;
	}
	
	function add_relation($bch1, $reltype, $bch2, $optdata) {
		if ($this->exists($bch1, $reltype, $bch2)) {
			$data = array();
			if ($bch1 != null) $data['bch1'] = $bch1;
			if ($reltype != null) $data['rel_type'] = $reltype;
			if ($bch2 != null) $data['bch2'] = $bch2;
			$this->db->where($data);
			
			$data = array();
			if ($optdata != null) $data['optdata'] = $optdata;
			$data['db_version'] = $this->get_next_db_version();
			$query = $this->db->update('cr_bch_relations', $data);
		}
		else if ($bch1 != $bch2){
			$data = array(
				'bch1' => $bch1,
				'rel_type' => $reltype,
				'bch2' => $bch2,
				'optdata' => $optdata,
				'db_version' => $this->get_next_db_version()
				);
			$query = $this->db->insert('cr_bch_relations', $data);
		}
	}

	function delete_relation($bch1, $reltype, $bch2) {
		$data = array();
		if ($bch1 != null) $data['bch1'] = $bch1;
		if ($reltype != null) $data['rel_type'] = $reltype;
		if ($bch2 != null) $data['bch2'] = $bch2;
		$this->db->where($data);
		$query = $this->db->delete('cr_bch_relations');
	}
	
	function exists($bch1, $reltype, $bch2) {
		$data = array(
			'bch1' => $bch1,
			'rel_type' => $reltype,
			'bch2' => $bch2
			);
		$this->db->where($data);
		$query = $this->db->get('cr_bch_relations');
		return ($query->num_rows() > 0);
	}

}
?>